/*
 *  Copyright (C) 2005-2007 Renier Roth
 *  www.renier.de
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package de.renier.vdr.channel.editor.container;

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.image.BufferedImage;
import java.util.Enumeration;
import java.util.Vector;

import javax.swing.JComponent;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

/**
 * AbstractTreeTransferHandler
 * 
 * @author <a href="mailto:editor@renier.de">Renier Roth</a>
 */
public abstract class AbstractTreeTransferHandler implements DragGestureListener, DragSourceListener,
    DropTargetListener {

  private DNDTree tree;
  private DragSource dragSource; // dragsource
  private DefaultMutableTreeNode draggedNodeParent;
  private Rectangle rect2D = new Rectangle();
  private boolean drawImage;

  protected AbstractTreeTransferHandler(DNDTree tree, int action, boolean drawIcon) {
    this.tree = tree;
    drawImage = drawIcon;
    dragSource = new DragSource();
    dragSource.createDefaultDragGestureRecognizer(tree, action, this);
    new DropTarget(tree, action, this);
  }

  /* Methods for DragSourceListener */
  public void dragDropEnd(DragSourceDropEvent dsde) {
    if (dsde.getDropSuccess() && dsde.getDropAction() == DnDConstants.ACTION_MOVE && draggedNodeParent != null) {
      try {
        Transferable transferable = dsde.getDragSourceContext().getTransferable();
        DefaultMutableTreeNode draggedNode = (DefaultMutableTreeNode) transferable
            .getTransferData(TransferableNode.NODE_FLAVOR);
        afterDrop(tree, draggedNode, dsde.getDropAction());
      } catch (Exception e) {
        e.printStackTrace();
      }
      ((DefaultTreeModel) tree.getModel()).nodeStructureChanged(draggedNodeParent);
    }
  }

  public final void dragEnter(DragSourceDragEvent dsde) {
    int action = dsde.getDropAction();
    if (action == DnDConstants.ACTION_COPY) {
      dsde.getDragSourceContext().setCursor(DragSource.DefaultCopyDrop);
    } else {
      if (action == DnDConstants.ACTION_MOVE) {
        dsde.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);
      } else {
        dsde.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);
      }
    }
  }

  public final void dragOver(DragSourceDragEvent dsde) {
    int action = dsde.getDropAction();
    if (action == DnDConstants.ACTION_COPY) {
      dsde.getDragSourceContext().setCursor(DragSource.DefaultCopyDrop);
    } else {
      if (action == DnDConstants.ACTION_MOVE) {
        dsde.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);
      } else {
        dsde.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);
      }
    }
  }

  public final void dropActionChanged(DragSourceDragEvent dsde) {
    int action = dsde.getDropAction();
    if (action == DnDConstants.ACTION_COPY) {
      dsde.getDragSourceContext().setCursor(DragSource.DefaultCopyDrop);
    } else {
      if (action == DnDConstants.ACTION_MOVE) {
        dsde.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);
      } else {
        dsde.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);
      }
    }
  }

  public final void dragExit(DragSourceEvent dse) {
    dse.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);
  }

  /* Methods for DragGestureListener */
  public final void dragGestureRecognized(DragGestureEvent dge) {
    TreePath path = tree.getSelectionPath();
    if (path != null) {
      DefaultMutableTreeNode draggedNode = (DefaultMutableTreeNode) path.getLastPathComponent();
      Vector expandedStates = new Vector();
      for (Enumeration enumeration = draggedNode.depthFirstEnumeration(); enumeration.hasMoreElements();) {
        DefaultMutableTreeNode element = (DefaultMutableTreeNode) enumeration.nextElement();
        TreePath treePath = new TreePath(element.getPath());
        expandedStates.add(new Boolean(tree.isExpanded(treePath)));
      }
      draggedNodeParent = (DefaultMutableTreeNode) draggedNode.getParent();
      if (drawImage) {
        // getpathbounds of
        Rectangle pathBounds = tree.getPathBounds(path);
        // selectionpath
        JComponent lbl = (JComponent) tree.getCellRenderer().getTreeCellRendererComponent(
                                                                                          tree,
                                                                                          draggedNode,
                                                                                          false,
                                                                                          tree.isExpanded(path),
                                                                                          ((DefaultTreeModel) tree
                                                                                              .getModel()).isLeaf(path
                                                                                              .getLastPathComponent()),
                                                                                          0, false);
        // setting bounds to lbl
        lbl.setBounds(pathBounds);
        // reference passing the label's ht and width
        TransferableNode.image = new BufferedImage(lbl.getWidth(), lbl.getHeight(),
            java.awt.image.BufferedImage.TYPE_INT_ARGB_PRE);
        // creating the graphics for buffered image
        Graphics2D graphics = TransferableNode.image.createGraphics();
        // Sets the Composite for the Graphics2D context
        graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f)); // Sets
        lbl.setOpaque(false);
        lbl.paint(graphics); // painting the graphics to label
        graphics.dispose();
      }
      dragSource.startDrag(dge, DragSource.DefaultMoveNoDrop, TransferableNode.image, new Point(0, 0),
                           new TransferableNode(draggedNode, expandedStates), this);
    }
  }

  /* Methods for DropTargetListener */

  public final void dragEnter(DropTargetDragEvent dtde) {
    Point pt = dtde.getLocation();
    int action = dtde.getDropAction();
    if (drawImage) {
      paintImage(pt);
    }
    try {
      if (canPerformAction(tree, TransferableNode.draggedNode, action, pt)) {
        dtde.acceptDrag(action);
      } else {
        dtde.rejectDrag();
      }
    } catch (Exception e) {
      dtde.rejectDrag();
    }
  }

  public final void dragExit(DropTargetEvent dte) {
    if (drawImage) {
      clearImage();
    }
  }

  public final void dragOver(DropTargetDragEvent dtde) {
    Point pt = dtde.getLocation();
    int action = dtde.getDropAction();
    tree.autoscroll(pt);
    if (drawImage) {
      paintImage(pt);
    }
    try {
      if (canPerformAction(tree, TransferableNode.draggedNode, action, pt)) {
        dtde.acceptDrag(action);
      } else {
        dtde.rejectDrag();
      }
    } catch (Exception e) {
      dtde.rejectDrag();
    }
  }

  public final void dropActionChanged(DropTargetDragEvent dtde) {
    Point pt = dtde.getLocation();
    int action = dtde.getDropAction();
    if (drawImage) {
      paintImage(pt);
    }
    try {
      if (canPerformAction(tree, TransferableNode.draggedNode, action, pt)) {
        dtde.acceptDrag(action);
      } else {
        dtde.rejectDrag();
      }
    } catch (Exception e) {
      dtde.rejectDrag();
    }
  }

  public final void drop(DropTargetDropEvent dtde) {
    try {
      if (drawImage) {
        clearImage();
      }
      int action = dtde.getDropAction();
      Transferable transferable = dtde.getTransferable();
      DefaultMutableTreeNode draggedNode = (DefaultMutableTreeNode) transferable
          .getTransferData(TransferableNode.NODE_FLAVOR);

      Point pt = dtde.getLocation();
      if (transferable.isDataFlavorSupported(TransferableNode.NODE_FLAVOR)
          && canPerformAction(tree, draggedNode, action, pt)) {
        TreePath pathTarget = tree.getPathForLocation(pt.x, pt.y);
        DefaultMutableTreeNode newParentNode = (DefaultMutableTreeNode) pathTarget.getLastPathComponent();
        Vector expandedStates = (Vector) transferable.getTransferData(TransferableNode.EXPANDED_STATE_FLAVOR);
        if (executeDrop(tree, draggedNode, newParentNode, expandedStates, action)) {
          dtde.acceptDrop(action);
          dtde.dropComplete(true);
          return;
        }
      }
      dtde.rejectDrop();
      dtde.dropComplete(false);
    } catch (Exception e) {
      System.out.println(e);
      dtde.rejectDrop();
      dtde.dropComplete(false);
    }
  }

  private final void paintImage(Point pt) {
    tree.paintImmediately(rect2D.getBounds());
    rect2D.setRect((int) pt.getX(), (int) pt.getY(), TransferableNode.image.getWidth(), TransferableNode.image
        .getHeight());
    tree.getGraphics().drawImage(TransferableNode.image, (int) pt.getX(), (int) pt.getY(), tree);
  }

  private final void clearImage() {
    tree.paintImmediately(rect2D.getBounds());
  }

  public abstract boolean canPerformAction(DNDTree target, DefaultMutableTreeNode draggedNode, int action,
      Point location);

  public abstract boolean executeDrop(DNDTree target, DefaultMutableTreeNode draggedNode,
      DefaultMutableTreeNode newParentNode, Vector expandedStates, int action);

  public abstract void afterDrop(DNDTree dndTree, DefaultMutableTreeNode draggedNode, int action);

}